package me.lwn.auth.config.mvc;

import me.lwn.auth.common.HttpMsg;
import me.lwn.auth.common.exception.MobileNotFoundException;
import me.lwn.auth.security.web.authentication.BadSmsCodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * @author lizhichao
 * @since 0.0.1
 */
@RestControllerAdvice
public class ResponseExceptionHandler extends ResponseEntityExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private ResponseEntity<?> doException(RuntimeException ex, WebRequest request) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpMsg<String> response = HttpMsg.fail(ex.getMessage());
        response.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        logger.error(ex.getMessage(), ex);
        return handleExceptionInternal(ex, response, headers, HttpStatus.INTERNAL_SERVER_ERROR, request);
    }

    @ExceptionHandler(MobileNotFoundException.class)
    public final ResponseEntity<?> handleMobileNotFoundException(MobileNotFoundException ex, WebRequest request) {
        return doException(ex, request);
    }

    @ExceptionHandler(BadSmsCodeException.class)
    public final ResponseEntity<?> handleBadSmsCodeException(BadSmsCodeException ex, WebRequest request) {
        return doException(ex, request);
    }
}